package assignment1.eventplan.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.location.Location;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;

import java.util.Locale;

import assignment1.eventplan.R;
import assignment1.eventplan.db.dao.EventPlanDao;
import assignment1.eventplan.db.master.EventPlanProvider;
import assignment1.eventplan.entity.EventPlan;
import assignment1.eventplan.request.MatrixRequestBuilder;
import assignment1.eventplan.request.MatrixResult;
import assignment1.eventplan.request.Request;
import assignment1.eventplan.request.Response;
import assignment1.eventplan.services.MapMatrixService;
import assignment1.eventplan.utils.DateUtil;
import assignment1.eventplan.utils.NotificationHelper;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private MapMatrixService.AlarmServiceController controller;
    private long eventId;
    private ServiceConnection connection;

    private EventPlan plan;
    private TextView titleText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (initData(null == savedInstanceState ? getIntent().getExtras() : savedInstanceState)) {
            setContentView(R.layout.activity_maps);
            initViews();
        } else {
            Toast.makeText(this, " miss event!!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void initViews() {
        titleText = (TextView) findViewById(R.id.title_text);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        bindService(new Intent(this, MapMatrixService.class), connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                controller = (MapMatrixService.AlarmServiceController) service;
                try2AddMarker();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                connection = null;
            }
        }, Activity.BIND_AUTO_CREATE);
    }

    private boolean initData(Bundle bundle) {
        if (null == bundle)
            return false;
        return (eventId = bundle.getLong(EventPlanDao.Field.ID, -1)) > 0;
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        try2AddMarker();
    }

    private void try2AddMarker() {
        if (null != controller && null != mMap) {
            Location lastLocation = controller.getLastKnownLocation();
            if (null == lastLocation)
                return;
            if (null == plan) {
                plan = EventPlanProvider.get().getEventById(eventId);
                if (null == plan) {
                    Toast.makeText(this, "miss event!!", Toast.LENGTH_SHORT).show();
                    finish();
                    return;
                }
            }

            // Add a marker in Sydney and move the camera
            LatLng myLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude());
            mMap.addMarker(new MarkerOptions().position(myLocation).title("my location"));


            mMap.addMarker(new MarkerOptions().position(plan.getLatLng()).title(plan.getAddressName()));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));


            MatrixRequestBuilder.obtain().originAddress(myLocation).destinationAddress(plan.getLatLng()).request(plan.getId(), new Request.RequestListener() {
                @Override
                public void onResponse(Request request, Response response) {
                    if (response.isSuccessful()) {
                        MatrixResult matrixResult = MatrixResult.obtain(response);
                        try {
                            if (null != matrixResult.error) {
                                return;
                            }
                            titleText.setText(String.format(Locale.getDefault(), "Duration= %s \n Distance= %s", matrixResult.getDurationText(), matrixResult.getDistanceText()));
                        } finally {
                            MatrixResult.recycle(matrixResult);
                        }

                    }
                }
            });
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != connection) {
            unbindService(connection);
            connection = null;
        }
    }
}
